//
//  NDPersonalViewModel.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/30.
//

import UIKit
import SwiftUI

class NDPersonalViewModel: ObservableObject {
    
    @Published var personalInfoModel: PersonalInfoModel?
    @Published var isLoading = false
    @Published var errorMessage: String?
    
    @Published var commonActionItemIndex = 0
    @Published var saveSuccess = false
    
    let productId: Int
    var orderNum: String?
    var startTimeStamp = 0
    
    init(productId: Int, orderNum: String) {
        self.productId = productId
        self.orderNum = orderNum
    }
    
    func createEnergyifyBinding(at index: Int, field: EnergyifyField) -> Binding<String> {
        return Binding(
            get: {
                guard let model = self.personalInfoModel,
                      index < model.energyify.count else { return "" }
                
                return self.getValueForField(model.energyify[index], field: field)
            },
            set: { newValue in
                self.updateEnergyifyField(at: index, field: field, value: newValue)
            }
        )
    }
    
    // 获取字段值
    private func getValueForField(_ energyify: Energyify, field: EnergyifyField) -> String {
        switch field {
        case .fatheraneity:
            return energyify.fatheraneity ?? ""
        case .olig:
            return energyify.olig ?? ""
        }
    }
    
    // 更新 energyify 中特定字段的方法
    func updateEnergyifyField(at index: Int, field: EnergyifyField, value: String) {
        guard var model = personalInfoModel,
              index < model.energyify.count else { return }
        
        // 根据字段类型更新对应的值
        switch field {
        case .fatheraneity:
            model.energyify[index].fatheraneity = value
        case .olig:
            model.energyify[index].olig = value
        }
        
        personalInfoModel = model
    }
    
    // 定义字段枚举
    enum EnergyifyField {
        case fatheraneity
        case olig
    }
   
    func requestPersonalInfo() {
        isLoading = true
        errorMessage = nil
        NDRequestManager.requestPersonalInfo(productId: productId) { [weak self] model, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.isLoading = false
                
                if let error = error {
                    self.errorMessage = error
                    return
                }
                
                guard let model = model else { return  }
                
                self.personalInfoModel = model
            }
        }
    }
    
    func requestSavePersonalInfo() {
        isLoading = true
        saveSuccess = false
        errorMessage = nil
        guard let energyify = personalInfoModel?.energyify else {
            errorMessage = localizedString("failed")
            return
        }
        NDRequestManager.requestSavePersonalInfo(productId: productId, energyifies: energyify) { [weak self] success, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                
                if let error = error {
                    self.errorMessage = error
                    self.isLoading = false
                    return
                }
                
                guard let success = success else { return  }
                self.saveSuccess = success
                self.isLoading = false
                
                NDEventAnallyticsTool.uploadMaiDianEvent(maiDianType: .personalCard,
                                                         productId: self.productId,
                                                         orderNum: self.orderNum,
                                                         startTimeStamp: self.startTimeStamp,
                                                         endTimeStamp: Int(Date().timeIntervalSince1970))
            }
        }
    }
    
    func requestAddressData() {
        let address = NDUserDefaults.shared.unarchiveObject(for: NDAddressKey, as: AddressModel.self)
        guard address == nil else { return }
        NDRequestManager.requestAddressInfo(productId: productId) { [weak self]  model, msg, error in
            guard let _ = self else { return }
            if error == nil,
               let model = model {
                NDUserDefaults.shared.archiveObject(model, for: NDAddressKey)
            }
        }
    }
    
    var courseatics: [Courseatic] {
        if let energyify = personalInfoModel?.energyify,
            energyify.count > commonActionItemIndex {
            return energyify[commonActionItemIndex].courseatic ?? []
        }
        return []
    }
    
    var title: String {
        if let energyify = personalInfoModel?.energyify,
            energyify.count > commonActionItemIndex {
            return energyify[commonActionItemIndex].pitister ?? ""
        }
        return ""
    }
}
